<template>
  <div class="sidebar-container" :class="{'hide-list': listHide}">
    <div class="node-type-list">
      <div v-for="(item, index) in groupList" @click="togglePanel(index)" class="node-type" :key="index" :class="classCom(item, index)">
        <svg-icon :icon-class="item.icon" className='icon'/>
        <div class="type-name">{{ item.name }}</div>
      </div>
    </div>

    <div class="node-list">
      <el-input v-if="showSearch" v-model.lazy="searchNode" class="search-input" placeholder="搜索节点">
        <i slot="prefix" class="el-input__icon el-icon-search"></i>
      </el-input>
      <div :class="`node-group group${index}`" v-for="(item, index) in filterNodeList[activeIndex]" :key="index">
        <div :class="`node-group-title ${item.name ? '' : 'empty-name'}`">
          <span>{{ item.name }}</span>
        </div>
        <div class="node-group-content">
          <template v-for="el in item.nodeList">
            <div v-if="el.configurationDescriptor.visible" :key="el.id" :class="`${NodeConfig[el.type].nodeClass} ${touchNode(el)}`" @mousedown="startDrag(el, $event)" @touchstart="startDrag(el, $event)" draggable class="ruleChain-node sidebar-node no-ports">
              <div class="node-main">
                <div class="left-area">
                  <div class="title">{{ el.name }}</div>
                  <div v-if="el.description" class="sub-title">{{ el.description }}</div>
                </div>
                <div class="node-icon">
                  <svg-icon :icon-class="el.icon" className='icon'/>
                </div>
              </div>
            </div>
          </template>
        </div>
      </div>
    </div>
    <div class="flex-collapse">
      <div class="node-collapse" @click='toggleListShow' :class="{'close': listHide}"></div>
    </div>
  </div>
</template>

<script>
import { deepClone } from '@/utils/helper/jsUtil'
import { NodeConfig } from '@/model/node.model'
import { mapState } from 'vuex'

export default {
  name: 'SideBar',
  data() {
    return {
      groupList: [],
      nodeList: [],
      filterNodeList: [],
      activeIndex: 0,
      searchNode: '',
      listHide: false,
      NodeConfig
    }
  },
  watch: {
    searchNode(val) {
      // if (val.trim() !== '') {
      const res = []
      this.nodeList[this.activeIndex].forEach(item => {
        const itemData = {
          nodeList: []
        }
        itemData.nodeList = item.nodeList.filter(el => {
          const exp = new RegExp(val, 'g')
          return exp.test(el.name)
        })
        if (item.name) {
          itemData.name = item.name
        }
        if (itemData.nodeList.length) {
          res.push(itemData)
        }
      })
      this.filterNodeList[this.activeIndex] = res
      // } else {
      //   this.filterNodeList[this.activeIndex] = this.nodeList[this.activeIndex]
      // }
      this.$forceUpdate()
    },
    allNodeList(val) {
      val.length && this.loadRuleNodeComponents()
    }
  },
  mounted() {
    this.allNodeList.length && this.loadRuleNodeComponents()
  },
  methods: {
    classCom(item, index) {
      return {
        [item.class]: true,
        'is-active': index === this.activeIndex
      }
    },
    touchNode(node) {
      return ['SceneLibAutoTouchNode', 'SceneLibAutoExitNode', 'SceneLibManualTouchNode', 'SceneLibManualExitNode', 'SceneLibFrontConditionNode'].includes(node.component) ? 'black-node' : ''
    },
    // 加载所有节点并渲染
    async loadRuleNodeComponents() {
      this.groupList = []
      this.nodeList = []
      this.filterNodeList = []

      // 隐藏产品或者自动触发产品不允许添加主动退出与主动触发节点
      if (this.productInfo.displayMethod === '0' || this.productInfo.triggerMethod === '0') {
        const nodeList = this.allNodeList.find(el => el.type === 'SCENE_NODE').nodeGroup[0].nodeList || []
        nodeList.filter(node => ['SceneLibManualTouchNode', 'SceneLibManualExitNode'].includes(node.component)).forEach(node => {
          node.configurationDescriptor.visible = false
        })
      }

      // 主动触发产品不允许添加自动触发节点与自动退出节点和历史判断节点
      if (this.productInfo.triggerMethod === '1') {
        const sceneList = this.allNodeList.find(el => el.type === 'SCENE_NODE').nodeGroup[0].nodeList || []
        sceneList.filter(node => ['SceneLibAutoTouchNode', 'SceneLibAutoExitNode'].includes(node.component)).forEach(node => {
          node.configurationDescriptor.visible = false
        })
        const advanceList = this.allNodeList.find(el => el.type === 'ADVANCED_NODE').nodeGroup[0].nodeList || []
        advanceList.find(node => node.component === 'AdvancedLibHistoricalNode').configurationDescriptor.visible = false
      }

      this.allNodeList.forEach(el => {
        this.groupList.push({
          icon: el.icon,
          name: el.name,
          class: NodeConfig[el.type].nodeClass
        })
        this.nodeList.push(el.nodeGroup)
        this.filterNodeList.push(el.nodeGroup)
      })
    },
    startDrag(data, e) {
      this.$emit('startDrag', data, e)
    },
    toggleListShow() {
      this.listHide = !this.listHide
      const width = document.body.clientWidth - (this.listHide ? 0 : 296)
      this.graph.resize(width, undefined)
    },
    togglePanel(index) {
      this.activeIndex = index
      this.searchNode = ''
      this.filterNodeList = deepClone(this.nodeList)
      this.$forceUpdate()
      if (index === 1) {
        // 下载产品文件便捷入口 快速点击车端服务三次
        window.hiddenDownload = 1 + window.hiddenDownload || 0
        if (window.hiddenDownload === 2) {
          this.$router.push({ path: `/ruleChains/d/${this.$route.params.id}` })
        } else { setTimeout(() => { window.hiddenDownload = undefined }, 1000) }
      }
    }
  },
  computed: {
    showSearch() {
      return this.groupList.length && ['scene-node', 'service-node', 'tsp-node', 'third-node'].includes(this.groupList[this.activeIndex].class)
    },
    ...mapState({
      productInfo: state => state.product.productInfo,
      allNodeList: state => state.product.nodeList,
      graph: state => state.graph.graph
    })
  }
}
</script>

<style lang="scss" scoped>
@import "~@/assets/styles/mixin.scss";
@import "~@/assets/styles/variables";

.sidebar-node {
  width: 200px;
  height: 56px;
}
.node-type-list {
  width: 65px;
  height: 100%;
  border-right: 1px solid $--border-color-base;
  .node-type {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 64px;
    height: 64px;
    margin-bottom: 8px;
    font-size: 12px;
    color: #666;
    cursor: pointer;
    &.is-active {
      @include node-color();
      color: $app-sidebar-text-active;
      .type-name{
        color: $app-sidebar-text-active;
      }
    }
    .icon {
      display: block;
      width: 20px;
      height: 40px;
    }
    .type-name{
      color: $--color-text-primary;
    }
  }
}

.node-list {
  padding: 16px;
  overflow: auto;
  scrollbar-width: none;
  &::-webkit-scrollbar {
        width: 0px;
    }
  .node-group {
    margin-bottom: 16px;
    .node-group-title {
      position: relative;
      height: 22px;
      line-height: 22px;
      margin-bottom: 8px;
      span {
        position: absolute;
        background: #fff;
        padding-right: 10px;
        overflow: hidden;
        text-overflow: ellipsis;
        height: 22px;
        max-width: 180px;
        white-space: nowrap;
        color: $--color-text-primary;
      }
      &::before {
        content: '';
        position: absolute;
        top: 50%;
        display: block;
        width: 100%;
        height: 1px;
        background: $--border-color-base;
      }
    }
    .ruleChain-node {
      margin-bottom: 8px;
      &:last-child {
        margin-bottom: 0;
      }
    }
    &.group0 .empty-name{
      display: none;
      height: 0;
      margin-bottom: 0;
    }
  }
  .search-input {
    margin-bottom: 16px;
  }
}
.flex-collapse{
  width: 12px;
  height: 98px;
  position: absolute;
  top: 40%;
  right: -12px;
  z-index: 500;
  .node-collapse{
    height: 12px;
    width: 98px;
    background: url("../../assets/bottom_drawer_open.png") center center no-repeat;
    transform-origin: 0 12px;
    transform: rotate(90deg);
    cursor: pointer;
    &.close{
      background: url("../../assets/bottom_drawer_close.png") center center no-repeat;
    }
  }
}
.sidebar-container{
  margin-left: 0;
  width: $app-sidebar-width;
  &.hide-list{
    margin-left: -$app-sidebar-width;
    width: 0;
  }
}
</style>
